"""
商品相关的数据验证模式
"""
from marshmallow import Schema, fields, validate, validates, ValidationError, post_load
from app.models.product import ProductStatus

class ProductSpecificationSchema(Schema):
    """商品规格数据验证模式"""
    id = fields.Integer(dump_only=True)
    name = fields.String(required=True, validate=validate.Length(min=1, max=50))
    options = fields.List(fields.String(), required=True, validate=validate.Length(min=1))

class ProductVariantSchema(Schema):
    """商品变体数据验证模式"""
    id = fields.Integer(dump_only=True)
    sku = fields.String(required=True, validate=validate.Length(min=3, max=50))
    price = fields.Decimal(required=True, validate=validate.Range(min=0))
    stock = fields.Integer(required=True, validate=validate.Range(min=0))
    specifications = fields.Dict(keys=fields.String(), values=fields.String(), required=True)
    created_at = fields.DateTime(dump_only=True)
    
    @validates('sku')
    def validate_sku(self, value):
        """验证SKU"""
        from app.models.product import ProductVariant
        variant = ProductVariant.query.filter_by(sku=value).first()
        if variant and variant.id != self.context.get('variant_id'):
            raise ValidationError('变体SKU已存在')
    
    @validates('specifications')
    def validate_specifications(self, value):
        """验证规格"""
        product_id = self.context.get('product_id')
        if not product_id:
            return
            
        from app.models.product import ProductSpecification
        specs = ProductSpecification.query.filter_by(product_id=product_id).all()
        
        # 检查规格名是否有效
        spec_names = {spec.name for spec in specs}
        for key in value.keys():
            if key not in spec_names:
                raise ValidationError(f'无效的规格名: {key}')
        
        # 检查规格值是否有效
        for spec in specs:
            if spec.name in value:
                if value[spec.name] not in spec.option_list:
                    raise ValidationError(f'规格"{spec.name}"的值"{value[spec.name]}"不在选项列表中')

class ProductSchema(Schema):
    """商品数据验证模式"""
    id = fields.Integer(dump_only=True)
    name = fields.String(required=True, validate=validate.Length(min=1, max=100))
    description = fields.String(allow_none=True)
    price = fields.Decimal(required=True, validate=validate.Range(min=0))
    stock = fields.Integer(required=True, validate=validate.Range(min=0))
    sku = fields.String(required=True, validate=validate.Length(min=3, max=50))
    status = fields.String(validate=validate.OneOf([status.value for status in ProductStatus]))
    created_at = fields.DateTime(dump_only=True)
    specifications = fields.List(fields.Nested(ProductSpecificationSchema), dump_only=True)
    variants = fields.List(fields.Nested(ProductVariantSchema), dump_only=True)
    
    @validates('sku')
    def validate_sku(self, value):
        """验证SKU"""
        from app.models.product import Product
        product = Product.query.filter_by(sku=value).first()
        if product and product.id != self.context.get('product_id'):
            raise ValidationError('商品SKU已存在')

class ProductCreateSchema(ProductSchema):
    """商品创建数据验证模式"""
    specifications = fields.List(fields.Nested(ProductSpecificationSchema), required=False)
    variants = fields.List(fields.Nested(ProductVariantSchema), required=False)
    
    @validates('variants')
    def validate_variants(self, value):
        """验证变体"""
        # 检查SKU唯一性
        skus = set()
        for variant in value:
            if variant.get('sku') in skus:
                raise ValidationError(f'变体SKU重复: {variant.get("sku")}')
            skus.add(variant.get('sku'))

class ProductUpdateSchema(Schema):
    """商品更新数据验证模式"""
    name = fields.String(validate=validate.Length(min=1, max=100))
    description = fields.String(allow_none=True)
    price = fields.Decimal(validate=validate.Range(min=0))
    stock = fields.Integer(validate=validate.Range(min=0))
    status = fields.String(validate=validate.OneOf([status.value for status in ProductStatus])) 